#include "KgLogFile.h"
#include <QDir>
#include <QTime>
//extern  stuControl_Cfg  g_ControlCfg;

KgLogFile::KgLogFile()
{
	//m_bIsLogSave = FALSE;
	//m_bCmdWindowOpen = FALSE;
	m_bCreateSuc = 0;
	//m_fpStdout = 0;
}

KgLogFile::~KgLogFile()
{
	//writelogfile("动态数据库卸载");
	if (m_bCreateSuc)
		m_file.close();
}

void  KgLogFile::createlogfile(QString fileName)
{
	m_strPath = QDir::currentPath();
	m_strPath += "/"+fileName;
	//QMessageBox::information(NULL, "title", m_strPath);

	//试着以追加方式打开
	m_file.setFileName(m_strPath);
    if (m_file.open(QIODevice::ReadWrite|QIODevice::Append))
	{
        //QMessageBox::information(NULL, "title", "step1");
		m_bCreateSuc = 1;
		printf("=================================create OK\n");
		//file.seek()
		return;
	}

    //上面打开失败了，试着以建立新文件方式打开
	if (m_file.open(QIODevice::WriteOnly))
	{
		//QMessageBox::information(NULL, "title", "step2");
		m_bCreateSuc = 1;
		printf("=================================create OK2\n");
		//file.SeekToEnd();
		return;
	}

	printf("=================================create fail\n");
}

int KgLogFile::fileSize()
{
   int size = 0;
   
   if (m_bCreateSuc)
   	{ 
   	   size = m_file.size();
   	}

   return size;
}

void KgLogFile::close()
{
    m_file.close();
}

void  KgLogFile::writelogfile(QString strInfo)
{
	if (/*m_bIsLogSave &&*/ m_bCreateSuc)
	{
	    if (m_file.size() >= 1024*1024*30)
		{
		   //printf("log file size:%d, too large cancel save\n", file.size());
		   return;
		}
		//printf("log file size:%d\n", file.size());
		
		m_criticfile.lock();
		QDateTime CurrentDateTime=QDateTime::currentDateTime();
		QString   str = CurrentDateTime.toString("yyyy-MM-dd hh:mm:ss ");
		strInfo = str+strInfo+"\r\n";
 		m_file.write(strInfo.toLocal8Bit());
		m_file.flush();
		m_criticfile.unlock();
		//if (/*g_ControlCfg.*/)
		//{
			//printf(strInfo);
		//}
	}
}
